function buildTree(items, parentIdField = 'pid', idField = 'id', orderField) {
  const itemMap = new Map()

  items.forEach((item) => {
    const node = { ...item, children: [] }
    const parentId = String(item[parentIdField])

    if (!itemMap.has(parentId)) {
      itemMap.set(parentId, [])
    }
    itemMap.get(parentId).push(node)
  })

  if (orderField) {
    itemMap.forEach((children) => {
      children.sort((a, b) => {
        return Number(a[orderField]) - Number(b[orderField])
      })
    })
  }

  function buildSubTree(parentId) {
    const children = itemMap.get(parentId) || []
    children.forEach((child) => {
      child.children = buildSubTree(String(child[idField]))
    })
    return children
  }

  return buildSubTree('0')
}

module.exports = {
  buildTree
}
